package com.laiyizhan.api.controller;

import com.laiyizhan.api.response.CodeApiResponse;
import com.laiyizhan.common.Constants;
import com.laiyizhan.common.code.CommonRspCode;
import com.laiyizhan.common.exception.BusinessException;
import com.laiyizhan.common.service.KvdbService;
import com.laiyizhan.common.utils.RandomUtils;
import com.laiyizhan.common.utils.Validator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 通用
 * Created by folie on 2016/12/28.
 */
@Controller
@RequestMapping("/api/common")
public class CommonApiController {

    private static final Logger log = LoggerFactory.getLogger(CommonApiController.class);

    @Autowired
    KvdbService kvdbService;

    /**
     * 获取验证码
     *
     * @param type   1 注册, 2 忘记密码
     * @param mobile
     * @return
     */
    @RequestMapping("/code")
    @ResponseBody
    public CodeApiResponse get_code(String type, String mobile) throws BusinessException {
        if (StringUtils.isBlank(type) || StringUtils.isBlank(mobile)) {
            throw new IllegalArgumentException();
        }
        // 校验手机号
        if (!Validator.isMobile(mobile)) {
            throw new BusinessException("手机号格式不正确");
        }
        String key = StringUtils.join(Constants.CODE, mobile);
        int count = kvdbService.getCountByKey(key);
        if (count >= 3) {
            throw new BusinessException("您今天请求的次数过多, 请改天再试");
        }
        CodeApiResponse response = new CodeApiResponse();
        String code = RandomUtils.genRandomNum(4);
        if (kvdbService.setObject(key, code)) {
            log.debug("code = {}", code);
            // 发送短信
            if ("1".equals(type)) {
                // TODO 注册短信
                response.setRespCode(CommonRspCode.FAILD.getCode());
                response.setRespMessage("发送失败");
            } else if ("2".equals(type)) {
                // TODO 忘记密码
                response.setRespCode(CommonRspCode.FAILD.getCode());
                response.setRespMessage("发送失败");
            }
        } else {
            response.setRespCode(CommonRspCode.FAILD.getCode());
            response.setRespMessage("获取验证码失败了");
        }
        return response;
    }
}
